package com.industrial.premu.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class FreemarkerUtils {

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    /**
     * 下载通过模板生成的文件
     * @param templateName 模板文件名
     * @param dataMap 数据
     * @param resp  响应对象
     * @param fileName  下载文件名
     */
    public void downlaodGenerateFile(String templateName, Map<String, Object> dataMap,
                                     HttpServletResponse resp, String fileName) throws IOException, TemplateException {
        // 配置文件下载
        resp.setHeader("content-type", "application/octet-stream");
        resp.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        resp.setCharacterEncoding("utf-8");

        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //生成excel xml
//        File file = ResourceUtils.getFile("classpath:ftl");
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        cfg.setDefaultEncoding("utf-8");
//        cfg.setDirectoryForTemplateLoading(file);
        cfg.setClassForTemplateLoading(this.getClass(), "/static/template");
        cfg.setNumberFormat("0.00");
        Template template = cfg.getTemplate(templateName,"utf-8");
//        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName,"utf-8");
        template.process(dataMap, resp.getWriter());

    }

}
